package com.eks.websocket.v2;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
@Component
@ServerEndpoint("/msg")
public class WebSocketServer {

    private static final CopyOnWriteArraySet<Session> sessionSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void open(Session session) {
        sessionSet.add(session);
        log.info("open... : {}", session.getId());
    }

    public void sendMessage(String message, String key) {
        sessionSet.stream().filter(session -> Objects.equals(session.getId(), key))
                .findFirst().ifPresent(session -> sendMessage(session, message));
    }

    public void sendMessage(String message) {
        sessionSet.forEach(session -> sendMessage(session, message));
    }

    private void sendMessage(Session session, String message){
        try{
            session.getBasicRemote().sendText(message);
        }catch (Exception ex){
            log.error("", ex);
        }
    }


    @OnClose
    public void onClose(Session session) {
        //从set中删除
        sessionSet.remove(session);
        log.info("onClose");
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("发生错误：，{}", throwable.toString());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到客户端发来的消息: {}", message);
    }


}
